package com.myself.service;

import com.myself.entity.Permission;
import com.myself.entity.Role;
import com.myself.entity.User;
import com.myself.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description:
 *
 * @Author: Liuzemin
 * @Date: 2020/7/10 15:53
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    PasswordHelper passwordHelper;

    @Override
    public User findById(Long id) {
        User user = userMapper.findById(id);

        // 因为数据库中`locked`字段使用的类型：`tinyint(1)`，
        // 那么使用mybatis查询数据库会自动将数据转换成boolean类型(使用了boolean类型接收)，0：false；1或其他非零数字：true
        System.out.println("是否锁定：" + user.getLocked());

        if (user == null) {
            return null;
        }
        return userMapper.findById(id);
    }

    @Override
    public void create(User user) {
        passwordHelper.encryptPassword(user);
        userMapper.create(user);
    }

    @Override
    public void delete(Long id) {
        userMapper.delete(id);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public User findByName(String username) {
        return userMapper.findByName(username);
    }

    @Override
    public List<Role> findRole(String username) {
        return userMapper.findRole(username);
    }

    @Override
    public List<Permission> findPermission(String username) {
        return userMapper.findPermission(username);
    }

    @Override
    public void correlationRoles(Long userId, Long... roleIds) {
        if (roleIds == null || roleIds.length == 0) {
            return;
        }
        for (Long roleId: roleIds) {
            if (!exists(userId, roleId)) {
                userMapper.correlationRoles(userId, roleId);
            }
        }
    }


    private boolean exists(Long userId, Long roleId) {
        return userMapper.exists(userId, roleId);
    }

    @Override
    public void deleteAllUserRoles(Long id) {
        userMapper.deleteAllUserRoles(id);
    }
}
